var redis = require("redis");
const config = require('config');
var client = redis.createClient(config.dbConfig.redis);
const defaultExpireTime = 864000000;

exports.keys = (key, callback) => {
    client.keys(key, (err, reply) => {
        callback(reply);
    });
}

exports.get = (key, callback) => {
    client.get(key, (err, reply) => {
        if (reply) {
            try {
                reply = JSON.parse(reply);
            } catch (err1) {
                reply = null;
            }
        }
        callback(reply);
    });
}

exports.set = (key, value) => {
    client.set(key, JSON.stringify(value), 'EX', defaultExpireTime);
}

exports.setWithExTime = (key, value, expireTime) => {
    client.set(key, JSON.stringify(value), 'EX', expireTime);
}

exports.del = (key) => {
    client.del(key);
}

exports.del1 = (key) => {
    client.del(key);
}

exports.llen = (key, callback) => {
    client.llen(key, (err, length) => {
        callback(length);
    });
}

exports.lpush = (key, value, callback) => {
    client.lpush(key, value);
    callback();
}

exports.rpush = (key, value) => {
    client.rpush(key, value);
}

exports.rpop = (key, callback) => {
    client.rpop(key, (err, reply) => {
        if (reply) {
            try {
                reply = JSON.parse(reply);
            } catch (err1) {
                reply = { error: true };
            }
        }
        callback(reply);
    });
}

exports.rpoplpush = (key1, key2, callback) => {
    client.rpoplpush(key1, key2, (err, reply) => {
        if (reply) {
            try {
                reply = JSON.parse(reply);
            } catch (err1) {
                reply = { error: true };
            }
        }
        callback(reply);
    });
}

exports.lrange = (key, start, stop, callback) => {
    client.lrange(key, start, stop, (err, reply) => {
        if (reply) {
            try {
                var result = [];
                for (var i in reply) {
                    result.push(JSON.parse(reply[i]));
                }
                reply = result;
            } catch (err1) {
                reply = { error: true };
            }
            callback(reply);
        } else {
            callback({});
        }
    });
}

exports.ltrim = (key, start, stop) => {
    client.lrange(key, start, stop);
}

client.on('error', function(err) {
    console.error('-------------------redis-error-------------------');
    console.error(err);
});